package exercise.iotest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class SocketServer {

    private static final int PORT =  15151;
    private volatile static Integer count = 0;
    private static final int maxCount = 100;
    private static ThreadPoolExecutor threadPoolForReportTask = new ThreadPoolExecutor(4, 8, 3, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(100), new ThreadPoolExecutor.CallerRunsPolicy());

    
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        while(true){
            System.out.println("服务端启动成功！");
            Socket socket = serverSocket.accept();
            changeCount(1);
            threadPoolForReportTask.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        call(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            System.out.println("连接数:"+count);
            if(count>maxCount){
                break;
            }
        }
        serverSocket.close();
        System.out.println("服务端关闭！");
    }
    
    private static void call(Socket socket) throws IOException{
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "UTF8");
        BufferedReader br = new BufferedReader(isr);
        String info;
        while((info=br.readLine())!=null){
            System.out.println("我是服务器，客户端说："+info);
        }
        socket.shutdownInput();
        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(os);
        pw.write("欢迎!");
        pw.flush();
        pw.close();
        os.close();
        br.close();
        isr.close();
        is.close();
        socket.close();
        changeCount(-1);
    }
    
    private static void changeCount(int i){
        synchronized (count) {
            count += i;
        }
    }

}
